package com.gxuwz.leave.dao;

import com.alibaba.druid.sql.dialect.blink.parser.BlinkStatementParser;
import com.gxuwz.leave.entity.Department;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class DepDaoImpl implements DepDao {
    private JdbcTemplate jdbcTemplate;

    @Override
    public void insert(Department entity) {
        String sql = "insert into sys_department(depID, depName) values (?, ?)";
        List<Object> paramList = new ArrayList<>();
        if(entity==null){
            return;
        }else{
            paramList.add(entity.getDepID());
            paramList.add(entity.getDepName());
        }
        jdbcTemplate.update(sql, paramList.toArray());
    }

    @Override
    public void delete(String depID) {
        String sql = "delete from sys_department where depID = ? ";
        if(depID==null||"".equals(depID)){
            return;
        }else{
            jdbcTemplate.update(sql, depID);
        }
    }

    @Override
    public void update(Department entity) {
        String sql = "update sys_department set ";
        List<Object> paramList = new ArrayList<>();
        if(entity ==null){
            return;
        }else{
            if(entity.getDepName()!=null && !"".equals(entity.getDepName())){
                sql+="depName = ?, ";
                paramList.add(entity.getDepName());
            }
            // 移除多余的逗号和空格
            sql = sql.substring(0, sql.length() - 2);
            sql+="where depID = ?";
            paramList.add(entity.getDepID());
        }
        jdbcTemplate.update(sql, paramList.toArray());
    }

    @Override
    public List<Department> query(Department entity) {
        String sql = "select * from sys_department where 1=1 ";
        List<Department> deps = new ArrayList<>();
        List<Object> paramList = new ArrayList<>();
        if(entity!=null){
            if(entity.getDepID()!=null && !"".equals(entity.getDepID())){
                sql+="and depID = ?";
                paramList.add(entity.getDepID());
            }
            if(entity.getDepName()!=null && !"".equals(entity.getDepName())){
                sql+="and depName like ?";
                paramList.add("%" + entity.getDepName() + "%");
            }
        }
        deps = jdbcTemplate.query(sql, new RowMapper<Department>() {
            @Override
            public Department mapRow(ResultSet resultSet, int i) throws SQLException {
                Department dep = new Department();
                dep.setDepID(resultSet.getString("depID"));
                dep.setDepName(resultSet.getString("depName"));
                return dep;
            }
        }, paramList.toArray());
        return deps;
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate){
        this.jdbcTemplate = jdbcTemplate;
    }
}
